
let util = require('./util')

//家族树的数据管理类
class FamilyTreeData {
  constructor() {
    this.origin_data = []  //原始数据
    this.with_level_data = [] //增加level字段，并按 level倒序，parent倒序 排列的数据。
  }

  //设置数据，格式为couple数组
  SetData(data) {
    this.origin_data = data
    if (!(data instanceof Array)) {
      throw "exception: family tree data is not array!"
    }
    //计算数据的level字段，并排序
    this._calcOriginDataLevel()
  }

  //计算原始数据中的level, 并对数据排序：level大的在前面，parent大的在前面，priority小(老大)的在后面。结果保存在变量with_level_data中
  _calcOriginDataLevel() {
    let origin_data = util.deepCopy(this.origin_data)
    //先搜集所有数据
    let parent_collect = [0]  //搜集所有父元素在parent_collect中的集合
    let level = 1  //从1开始
    while (true) {
      let arr = origin_data.filterAndRemove(item => parent_collect.includes(item.parent))
      if (parent_collect.length == 1 && parent_collect[0] == 0) {
        //顶级节点
        if (arr.length != 1) {
          throw "exception: family tree data support only one level 1 node!"
        }
      }
      if (arr.length == 0) {
        break
      }

      for (let i = 0; i < arr.length; i++) {
        arr[i].level = level
      }
      this.with_level_data = [...this.with_level_data, ...arr]

      parent_collect = arr.map(item => item.child)
      level++
    }
    //再排序
    this.with_level_data.sort((item1, item2) => {
      if (item1.level < item2.level) {
        return 1
      } else if (item1.level > item2.level) {
        return -1
      }

      if (item1.parent < item2.parent) {
        return 1
      } else if (item1.parent > item2.parent) {
        return -1
      }

      if (item1.priority < item2.priority) {
        return 1
      } else if (item1.priority > item2.priority) {
        return -1
      }

      return 0
    })
    console.log('sort data:', this.with_level_data)
  }
}

module.exports = {
  FamilyTreeData
}